package com.cn.wanxi.springsecurity.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName = "crossOriginFilter", urlPatterns = {"/*"})
public class CrossOriginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        response.setHeader("content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        //获取客户端的请求地址
        String origin = request.getHeader("Origin");
        //把该地址设置为客户端可与请求的地址
        response.setHeader("Access-Control-Allow-Origin", origin);
        //设置接口支持的请求方式
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        //允许客户端可以使用当前请求头,其实就是允许自定义的请求头
        response.setHeader("Access-Control-Allow-Headers", "token, codeKey, x-requested-with, Authorization");
        //客户端请求头认证，默认为false, 需要设置为true
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String method = request.getMethod();
        //允许客户端请求验证，如果客户端请求验证通过，返回Success到客户端，通知客户端进行第二次正常访问。
        if (method.equalsIgnoreCase("OPTIONS")) {
            response.getOutputStream().write("Success".getBytes("utf-8"));
        } else {
            filterChain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }
}
